package com.paomi.client.activity.address;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.paomi.client.R;
import com.paomi.client.activity.address.View.AddAddressView;
import com.paomi.client.activity.address.View.CityBean;
import com.paomi.client.activity.address.presenter.AddAddressPre;
import com.paomi.client.base.BaseMvpActivity;
import com.paomi.client.bean.AddressInfo;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.Util;
import com.paomi.client.view.CityNumberPicker;
import com.paomi.client.view.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddAddressActivity extends BaseMvpActivity<AddAddressView, AddAddressPre> implements AddAddressView {
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.button_goback)
    TextView button_goback;
    @BindView(R.id.tv_cord)
    TextView tv_cord;
    @BindView(R.id.tv_location_detail)
    TextView tv_location_detail;
    @BindView(R.id.check_box)
    CheckBox check_box;
    Dialog cordDialog;

    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_content)
    EditText et_content;

    List<String> list = new ArrayList<>();

    Dialog chooseCityDialog;
    CityNumberPicker np0;
    CityNumberPicker np1;
    CityNumberPicker np2;
    //    JSONObject areaJSON;
    Boolean districtSelected = false;

    public String province;
    public String provinceId;
    public String city;
    public String cityId;
    public String area;
    public String areaId;

    AddressInfo info = null;
    List<CityBean.ReturnData> provinceList = new ArrayList<>();
    List<CityBean.ReturnData> cityList = new ArrayList<>();
    List<CityBean.ReturnData> areaList = new ArrayList<>();
    @BindView(R.id.btn_delete)
    Button btnDelete;

    @NonNull
    @Override
    public AddAddressPre createPresenter() {
        return new AddAddressPre();
    }

    @Override
    protected String setTitle() {
        return getResources().getString(R.string.receive_address);
    }

    @Override
    protected void showBack(TextView button_goback) {
        button_goback.setVisibility(View.VISIBLE);
    }

    @NonNull
    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_address;
    }

    @Override
    protected void initEvent() {
        button_goback.setTypeface(iconfont);
        tv_phone.setTypeface(iconfont);
        tv_location.setTypeface(iconfont);
        button_goback.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        button_goback.setTextColor(getResources().getColor(R.color.main_color));
        button_goback.setText(getResources().getString(R.string.back_normal) + getResources().getString(R.string.back));
//        try {
//            areaJSON = new JSONObject(loadJSONFromAsset());
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        info = (AddressInfo) getIntent().getSerializableExtra("AddressInfo");
        test();
        getPresenter().getProvince("100000");

        if (info != null) {
            btnDelete.setVisibility(View.VISIBLE);
            et_name.setText(info.getName());
            et_phone.setText(info.getMobile());
            et_content.setText(info.getAddress());
            tv_location_detail.setText(info.getProvince() + info.getCity() + info.getDistrict());
            province = info.getProvince();
            city = info.getCity();
            area = info.getDistrict();
            if (info.isDefault()) {
                check_box.setChecked(true);
            } else {
                check_box.setChecked(false);
            }
        }

    }

    void test() {
        list.add("中国大陆 +86");
        list.add("香港 +852");
        list.add("澳门 +853");
        list.add("台湾 +886");
    }

    @OnClick(R.id.tv_cord)
    void chooseCord() {
        cordDialog = new Dialog(AddAddressActivity.this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(AddAddressActivity.this).inflate(R.layout.layout_choose_areacode, null);
        cordDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        cordDialog.setCanceledOnTouchOutside(true);
        cordDialog.getWindow().setGravity(Gravity.BOTTOM);
        TextView success = cordDialog.findViewById(R.id.tv_success);
        TextView cancel = cordDialog.findViewById(R.id.tv_cancel);
        WheelView wheelView = cordDialog.findViewById(R.id.whellView);
        wheelView.setOffset(2);
        wheelView.setItems(list);
        wheelView.setSeletion(0);
        success.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String select = wheelView.getSeletedItem();
                int begin = select.indexOf("+");
                tv_cord.setText(select.substring(begin, select.length()));
                cordDialog.cancel();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cordDialog != null) {
                    cordDialog.cancel();
                }
            }
        });
        cordDialog.show();
    }

    @OnClick({R.id.ll_choose, R.id.tv_location_detail})
    void chooseDistrict() {
        chooseCityDialog.show();
    }

    void createChooseCity() {
        if (chooseCityDialog == null) {
            chooseCityDialog = new Dialog(AddAddressActivity.this, R.style.BottomDialog);
            View contentView = LayoutInflater.from(AddAddressActivity.this).inflate(R.layout.dialog_address_picker, null);
            chooseCityDialog.setContentView(contentView);
            ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
            layoutParams.width = getResources().getDisplayMetrics().widthPixels;
            contentView.setLayoutParams(layoutParams);
            chooseCityDialog.setCanceledOnTouchOutside(true);
            chooseCityDialog.getWindow().setGravity(Gravity.BOTTOM);

            np0 = (CityNumberPicker) chooseCityDialog.findViewById(R.id.numberPicker1);
            np1 = (CityNumberPicker) chooseCityDialog.findViewById(R.id.numberPicker2);
            np2 = (CityNumberPicker) chooseCityDialog.findViewById(R.id.numberPicker3);

            np2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
            np1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
            np0.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

            np0.setWrapSelectorWheel(false);
            np1.setWrapSelectorWheel(false);
            np2.setWrapSelectorWheel(false);

            setPickerValues(np0, provinceList);
            np0.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    provinceId = provinceList.get(newVal).getId() + "";
                    getPresenter().getCity(provinceId);
//                    try {
//                        JSONObject secondLevel = areaJSON.getJSONObject(picker.getDisplayedValues()[newVal]);
//                        setPickerValues(np1, secondLevel);
//                        JSONArray thirdLevel = secondLevel.getJSONArray(np1.getDisplayedValues()[0]);
//                        setThirdLevel(np2, thirdLevel);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }
            });
            np1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    cityId = cityList.get(newVal).getId() + "";
                    getPresenter().getArea(cityId);
//                    try {
//                        JSONObject secondLevel = areaJSON.getJSONObject(np0.getDisplayedValues()[np0.getValue()]);
//                        JSONArray thirdLevel = secondLevel.getJSONArray(picker.getDisplayedValues()[newVal]);
//                        setThirdLevel(np2, thirdLevel);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }
            });
            np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    areaId = areaList.get(newVal).getId() + "";
                }
            });
//            try {
//                JSONObject secondLevel = areaJSON.getJSONObject(np0.getDisplayedValues()[0]);
//                String[] finalSecondStringArray = setPickerValues(np1, secondLevel);
//                JSONArray thirdLevel = secondLevel.getJSONArray(finalSecondStringArray[0]);
//                setThirdLevel(np2, thirdLevel);
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }

            getPresenter().setNumberPickerDividerColor(np0, AddAddressActivity.this);
            getPresenter().setNumberPickerDividerColor(np1, AddAddressActivity.this);
            getPresenter().setNumberPickerDividerColor(np2, AddAddressActivity.this);

            chooseCityDialog.findViewById(R.id.tv_success).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    districtSelected = true;
                    tv_location_detail.setText(np0.getDisplayedValues()[np0.getValue()] + " "
                            + np1.getDisplayedValues()[np1.getValue()] + " "
                            + np2.getDisplayedValues()[np2.getValue()]);
                    province = np0.getDisplayedValues()[np0.getValue()];
                    city = np1.getDisplayedValues()[np1.getValue()];
                    area = np2.getDisplayedValues()[np2.getValue()];
                    chooseCityDialog.dismiss();
                }
            });

            chooseCityDialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    chooseCityDialog.dismiss();
                }
            });
        }
    }

    protected String[] setPickerValues(CityNumberPicker picker, List<CityBean.ReturnData> jsonObject) {
//        Iterator iterator = jsonObject.keys();
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < jsonObject.size(); i++) {
            list.add(jsonObject.get(i).getName());
        }
//        while (iterator.hasNext()) {
//            String key = (String) iterator.next();
//            list.add(key);
//        }

        String[] mStringArray = new String[list.size()];
        mStringArray = list.toArray(mStringArray);


        picker.setMinValue(0);
        picker.setMaxValue(0);
        picker.setDisplayedValues(mStringArray);
        picker.setMaxValue(list.size() - 1);

        return mStringArray;
    }

//    private String loadJSONFromAsset() {
//        String json = null;
//        try {
//            InputStream is = getAssets().open("areas.json");
//            int size = is.available();
//            byte[] buffer = new byte[size];
//            is.read(buffer);
//            is.close();
//            json = new String(buffer, "UTF-8");
//        } catch (IOException ex) {
//            ex.printStackTrace();
//            return null;
//        }
//        return json;
//    }

    protected void setThirdLevel(CityNumberPicker np2, List<CityBean.ReturnData> thirdLevel) {
        ArrayList<String> list2 = new ArrayList<>();

//            for (int i = 0; i < thirdLevel.length(); i++) {
//                list2.add(thirdLevel.getString(i));
//
//                String[] mStringArray2 = new String[list2.size()];
//                mStringArray2 = list2.toArray(mStringArray2);
//
//                np2.setMinValue(0);
//                np2.setMaxValue(0);
//                np2.setDisplayedValues(mStringArray2);
//                np2.setMaxValue(list2.size() - 1);
//            }
        for (int i = 0; i < thirdLevel.size(); i++) {
            list2.add(thirdLevel.get(i).getName());
            String[] mStringArray2 = new String[list2.size()];
            mStringArray2 = list2.toArray(mStringArray2);

            np2.setMinValue(0);
            np2.setMaxValue(0);
            np2.setDisplayedValues(mStringArray2);
            np2.setMaxValue(list2.size() - 1);
        }
    }

    @OnClick(R.id.tv_save)
    void saveOrChange() {
        if (et_name.getText().toString().trim().isEmpty()) {
            Util.toast(this, getResources().getString(R.string.address_toast_name));
            return;
        } else if (et_phone.getText().toString().trim().isEmpty()) {
            Util.toast(this, getResources().getString(R.string.address_toast_phone));
            return;
        } else if (tv_location_detail.getText().toString().isEmpty()) {
            Util.toast(this, getResources().getString(R.string.address_toast_province));
            return;
        } else if (et_content.getText().toString().trim().isEmpty()) {
            Util.toast(this, getResources().getString(R.string.address_toast_content));
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        if (info != null) {
            map.put("opt", "update");//操作方式 save添加 update修改
            map.put("id", info.getId() + "");//收货地址ID 修改时必选
        } else {
            map.put("opt", "save");//操作方式 save添加 update修改
        }
        map.put("name", et_name.getText().toString().trim());//收件人姓名
        map.put("mobile", et_phone.getText().toString().trim());//联系方式
        map.put("province", province);//省
        map.put("city", city);//市
        map.put("district", area);//区
        map.put("address", et_content.getText().toString().trim());//详细地址
        map.put("postcode", "");//邮编
        map.put("provinceId", provinceId);//省Id
        map.put("cityId", cityId);//市Id
        map.put("districtId", areaId);//区Id
        if (check_box.isChecked()) {
            map.put("isDefault", "true");//是否默认收货地址 true默认 false不默认
        } else {
            map.put("isDefault", "false");//是否默认收货地址 true默认 false不默认
        }
        map.put("remark", "");//备注

        getPresenter().saveBtn(this,map);
    }

    @Override
    public void addAddressSuccess(BaseJSON json) {
        if (json.returnCode.equals("0000") && json.returnMessage.equals("操作成功")) {
            if (info == null) {
                Util.toast(this, "保存成功");
            } else {
                Util.toast(this, "修改成功");
            }
            finish();
        } else {
            Util.toast(this, json.returnMessage);
        }
    }

    @Override
    public void showProvince(CityBean json) {
        provinceList.clear();
        provinceList.addAll(json.getReturnData());
        getPresenter().getCity(provinceList.get(0).getId() + "");
        provinceId = provinceList.get(0).getId() + "";
        createChooseCity();
    }

    @Override
    public void showCity(CityBean json) {
        cityList.clear();
        cityList.addAll(json.getReturnData());
        setPickerValues(np1, cityList);
        getPresenter().getArea(cityList.get(0).getId() + "");
        cityId = cityList.get(0).getId() + "";
    }

    @Override
    public void showArea(CityBean json) {
        areaList.clear();
        areaList.addAll(json.getReturnData());
        setThirdLevel(np2, areaList);
        areaId = areaList.get(0).getId() + "";
    }

    /**
     * 删除操作
     */
    @OnClick(R.id.btn_delete)
    public void onViewClicked() {
        getPresenter().deleteBtn(this,""+info.getId());
    }

    /**
     * 删除成功操作
     * @param baseJSON
     */
    @Override
    public void deleteSuccess(BaseJSON baseJSON) {
        ToastUtil.getToastEmail().ToastShow(this, null, 1, R.layout.toast_view, getResources().getString(R.string.delete_success));
        finish();
    }
}
